package com.ruoyi.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
public class PDFUtils {


    public static Document createDocument(String path) {
        /** 实例化文档对象 */
        Document document = new Document(PageSize.A4, 20, 20, 20, 20);
        /** 创建 PdfWriter 对象 */
        try {
            PdfWriter.getInstance(document,// 文档对象的引用
                    new FileOutputStream(path));//文件的输出路径+文件的实际名称
        } catch (Exception e) {
            throw new ClassCastException(e.getMessage());
        }
        document.open();// 打开文档
        return document;
    }

    public static boolean createDeviceDate(Document document, List<List<Map<String,Object>>> rows, String startTime, String endTime){
        try {
            /** pdf文档中中文字体的设置，注意一定要添加iTextAsian.jar包 */
            BaseFont bfChinese = BaseFont.createFont("STSong-Light",
                    "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font font = new com.itextpdf.text.Font(bfChinese, 10, Font.NORMAL);//加入document：
            Font tableFont = new com.itextpdf.text.Font(bfChinese, 7, Font.NORMAL);//加入document：
            Font ParagraphFont = new com.itextpdf.text.Font(bfChinese, 16, Font.NORMAL);//加入document：
            Font BigFont = new com.itextpdf.text.Font(bfChinese, 20, Font.NORMAL);//加入document：
            Paragraph title = new Paragraph("产品数据统计", BigFont);
            title.setAlignment(1);
            title.setSpacingBefore(10);
            title.setSpacingAfter(10);
            Chapter chapter = new Chapter(title, 1);
            chapter.setNumberDepth(0);
            for (int i = 0; i < rows.size(); i++) {
                /** 创建章节对象 */
                //产品的三个数据
                List<Map<String,Object>> mapList = rows.get(i);
                if (CollUtil.isEmpty(mapList)){
                    continue;
                }
                Map<String, Object> map = mapList.get(0);
                String deviceName = (String) map.get("deviceName");
                Paragraph titleName = new Paragraph(deviceName, ParagraphFont);
                titleName.setAlignment(1);
                titleName.setSpacingBefore(10);
                titleName.setSpacingAfter(10);
                Section section = chapter.addSection(titleName);
                if (i > 0){
                    section.setTriggerNewPage(true);
                }
                for (Map<String,Object> dataMap : mapList) {
                    String number = (String) dataMap.get("number");
                    if (StrUtil.equals(number,"1")){
                        List<String> columns = (List<String>) dataMap.get("columns");
                        List<List<Map<String, String>>> data = (List<List<Map<String, String>>>) dataMap.get("data");
                        /** 创建章节中的小节 */
                        Paragraph sectionName = new Paragraph("点位数据", ParagraphFont);
                        sectionName.setAlignment(1);
                        sectionName.setSpacingBefore(10);
                        sectionName.setSpacingAfter(10);
                        Section sectionElement = section.addSection(sectionName);
                        Paragraph timeTitle = new Paragraph(startTime + " - " + endTime, ParagraphFont);
                        timeTitle.setAlignment(1);
                        timeTitle.setSpacingAfter(30);
                        sectionElement.add(timeTitle);
                        /** 创建表格对象（包含行列矩阵的表格） */
                        PdfPTable t1 = new PdfPTable(columns.size());// 设置总列宽
                        t1.setPaddingTop(5);
                        t1.setSpacingBefore(5);
                        t1.setSpacingAfter(5);
                        t1.setTotalWidth(550);//表格总宽度
                        t1.setLockedWidth(true);//锁定宽度
                        for (String identifier : columns) {
                            PdfPCell c = new PdfPCell(new Paragraph(identifier, font));
                            c.setUseAscender(true);
                            c.setVerticalAlignment(Element.ALIGN_MIDDLE);
                            t1.addCell(c);
                        }
                        // 第二行开始不需要new Cell()
                        for (List<Map<String, String>> dataValue : data) {
                            for (Map<String, String> value : dataValue) {
                                t1.addCell(new Paragraph(value.get("data"), tableFont));
                            }
                        }
                        sectionElement.add(t1);
                    }
                    if (StrUtil.equals(number,"2")){
                        List<String> columns = (List<String>) dataMap.get("columns");
                        List<List<Map<String, String>>> data = (List<List<Map<String, String>>>) dataMap.get("data");
                        /** 创建章节中的小节 */
                        Paragraph sectionName = new Paragraph("活跃数据", ParagraphFont);
                        sectionName.setAlignment(1);
                        sectionName.setSpacingBefore(10);
                        sectionName.setSpacingAfter(10);
                        Section sectionElement = section.addSection(sectionName);
                        sectionElement.setTriggerNewPage(true);
                        Paragraph timeTitle = new Paragraph(startTime + " - " + endTime, ParagraphFont);
                        timeTitle.setAlignment(1);
                        timeTitle.setSpacingAfter(30);
                        sectionElement.add(timeTitle);
                        /** 创建表格对象（包含行列矩阵的表格） */
                        PdfPTable t1 = new PdfPTable(columns.size());// 设置总列宽
                        t1.setPaddingTop(5);
                        t1.setSpacingBefore(5);
                        t1.setSpacingAfter(5);
                        t1.setTotalWidth(550);//表格总宽度
                        t1.setLockedWidth(true);//锁定宽度
                        for (String identifier : columns) {
                            PdfPCell c = new PdfPCell(new Paragraph(identifier, font));
                            c.setUseAscender(true);
                            c.setVerticalAlignment(Element.ALIGN_MIDDLE);
                            t1.addCell(c);
                        }
                        // 第二行开始不需要new Cell()
                        for (List<Map<String, String>> dataValue : data) {
                            for (Map<String, String> value : dataValue) {
                                if (value.get("name").contains("time")) {
                                    t1.addCell(new Paragraph(value.get("data"), tableFont));
                                    continue;
                                }
                                String status = null;
                                if (StrUtil.isBlank(Convert.toStr(value.get("data")))) {
                                    status = "";
                                }
                                if (StrUtil.equals(Convert.toStr(value.get("data")), "1")) {
                                    status = "在线";
                                } else if (StrUtil.equals(Convert.toStr(value.get("data")), "0")) {
                                    status = "离线";
                                }
                                t1.addCell(new Paragraph(status, tableFont));
                            }
                        }
                        section.add(t1);
                    }
                    if (StrUtil.equals(number,"3")){
                        List<Map<String, String>> columns = (List<Map<String, String>>) dataMap.get("columns");
                        List<List<Map<String,String>>> data = (List<List<Map<String,String>>>) dataMap.get("data");
                        /** 创建章节中的小节 */
                        Paragraph sectionName = new Paragraph("事件数据", ParagraphFont);
                        sectionName.setAlignment(1);
                        sectionName.setSpacingBefore(10);
                        sectionName.setSpacingAfter(10);
                        Section sectionElement = section.addSection(sectionName);
                        sectionElement.setTriggerNewPage(true);
                        Paragraph timeTitle = new Paragraph(startTime + " - " + endTime, ParagraphFont);
                        timeTitle.setAlignment(1);
                        timeTitle.setSpacingAfter(30);
                        sectionElement.add(timeTitle);
                        /** 创建表格对象（包含行列矩阵的表格） */
                        PdfPTable t1 = new PdfPTable(columns.size());// 设置总列宽
                        t1.setPaddingTop(5);
                        t1.setSpacingBefore(5);
                        t1.setSpacingAfter(5);
                        t1.setTotalWidth(550);//表格总宽度
                        t1.setLockedWidth(true);//锁定宽度
                        for (Map<String, String> identifierMap : columns) {
                            PdfPCell c = new PdfPCell(new Paragraph(identifierMap.get("name"), font));
                            c.setUseAscender(true);
                            c.setVerticalAlignment(Element.ALIGN_MIDDLE);
                            t1.addCell(c);
                        }
                        // 第二行开始不需要new Cell()
                        for (List<Map<String,String>> dataValue : data) {
                            for (Map<String,String> value : dataValue) {
                                t1.addCell(new Paragraph(value.get("data"), tableFont));
                            }
                        }
                        sectionElement.add(t1);
                    }
                }
            }
            document.add(chapter);
            return true;
        } catch (Exception e2) {
            throw new ClassCastException(e2.getMessage());
        }
    }

    /**
     * 生成没有时间范围的列表数据
     * @return
     */
    public static boolean createNotDataList(Document document, List<Map<String,String>> columns, String sheetName, List<List<Map<String,String>>> rows) {
        try {
            /** pdf文档中中文字体的设置，注意一定要添加iTextAsian.jar包 */
            BaseFont bfChinese = BaseFont.createFont("STSong-Light",
                    "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font font = new com.itextpdf.text.Font(bfChinese, 10, Font.NORMAL);//加入document：
            Font tableFont = new com.itextpdf.text.Font(bfChinese, 7, Font.NORMAL);//加入document：
            Font ParagraphFont = new com.itextpdf.text.Font(bfChinese, 16, Font.NORMAL);//加入document：
            Font BigFont = new com.itextpdf.text.Font(bfChinese, 20, Font.NORMAL);//加入document：
            /** 创建章节对象 */
            Paragraph title = new Paragraph(sheetName, BigFont);
            title.setAlignment(1);
            title.setSpacingBefore(10);
            title.setSpacingAfter(10);
            Chapter chapter = new Chapter(title, 1);
            chapter.setNumberDepth(0);
            /** 创建章节中的小节 */
//            Paragraph titleName = new Paragraph("点位数据", ParagraphFont);
//            titleName.setAlignment(1);
//            titleName.setSpacingBefore(10);
//            titleName.setSpacingAfter(10);
            Section section = chapter.addSection("查看",0);
            /** 创建表格对象（包含行列矩阵的表格） */
            PdfPTable t1 = new PdfPTable(columns.size());// 设置总列宽
            t1.setPaddingTop(5);
            t1.setSpacingBefore(5);
            t1.setSpacingAfter(5);
            t1.setTotalWidth(550);//表格总宽度
            t1.setLockedWidth(true);//锁定宽度
            for (Map<String,String> map : columns) {
                PdfPCell c = new PdfPCell(new Paragraph(map.get("name"), font));
                c.setUseAscender(true);
                c.setVerticalAlignment(Element.ALIGN_MIDDLE);
                t1.addCell(c);
            }
            // 第二行开始不需要new Cell()
            for (List<Map<String,String>> dataValue : rows) {
                for (Map<String,String> map : dataValue) {
                    t1.addCell(new Paragraph(map.get("data"), tableFont));
                }
            }
            section.add(t1);
            document.add(chapter);
            return true;
        }catch (Exception e){
            throw new ClassCastException(e.getMessage());
        }
    }

    /**
     * 生成有时间范围的列表数据
     *
     * @return
     */
    public static boolean createDataList(Document document, List<Map<String,String>> columns, String sheetName, List<List<Map<String,String>>> rows, String startTime, String endTime) {
        try {
            /** pdf文档中中文字体的设置，注意一定要添加iTextAsian.jar包 */
            BaseFont bfChinese = BaseFont.createFont("STSong-Light",
                    "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font font = new com.itextpdf.text.Font(bfChinese, 10, Font.NORMAL);//加入document：
            Font tableFont = new com.itextpdf.text.Font(bfChinese, 7, Font.NORMAL);//加入document：
            Font ParagraphFont = new com.itextpdf.text.Font(bfChinese, 16, Font.NORMAL);//加入document：
            Font BigFont = new com.itextpdf.text.Font(bfChinese, 20, Font.NORMAL);//加入document：
            /** 创建章节对象 */
            Paragraph title = new Paragraph(sheetName, BigFont);
            title.setAlignment(1);
            title.setSpacingBefore(10);
            title.setSpacingAfter(10);
            Chapter chapter = new Chapter(title, 1);
            chapter.setNumberDepth(0);
            /** 创建章节中的小节 */
//            Paragraph titleName = new Paragraph("点位数据", ParagraphFont);
//            titleName.setAlignment(1);
//            titleName.setSpacingBefore(10);
//            titleName.setSpacingAfter(10);
            Section section = chapter.addSection("查看",0);
            Paragraph timeTitle = new Paragraph(startTime + " - " + endTime, ParagraphFont);
            timeTitle.setAlignment(1);
            timeTitle.setSpacingAfter(30);
            section.add(timeTitle);
            /** 创建表格对象（包含行列矩阵的表格） */
            PdfPTable t1 = new PdfPTable(columns.size());// 设置总列宽
            t1.setPaddingTop(5);
            t1.setSpacingBefore(5);
            t1.setSpacingAfter(5);
            t1.setTotalWidth(550);//表格总宽度
            t1.setLockedWidth(true);//锁定宽度
            for (Map<String,String> map : columns) {
                PdfPCell c = new PdfPCell(new Paragraph(map.get("name"), font));
                c.setUseAscender(true);
                c.setVerticalAlignment(Element.ALIGN_MIDDLE);
                t1.addCell(c);
            }
            // 第二行开始不需要new Cell()
            for (List<Map<String,String>> dataValue : rows) {
                for (Map<String,String> value : dataValue) {
                    t1.addCell(new Paragraph(value.get("data"), tableFont));
                }
            }
            section.add(t1);
            document.add(chapter);
            return true;
        }catch (Exception e){
            throw new ClassCastException(e.getMessage());
        }
    }

    /**
     * 生成报表PDF
     *
     * @param data        报表数据
     * @param startTime   统计开始时间
     * @param endTime     统计结束时间
     * @param deviceNames 产品名称集合
     * @return
     */
    public static boolean createDeviceDatePdf(Document document, List<Map<String, Object>> data, String startTime, String endTime, String deviceNames) {
        try {
            /** pdf文档中中文字体的设置，注意一定要添加iTextAsian.jar包 */
            BaseFont bfChinese = BaseFont.createFont("STSong-Light",
                    "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font font = new com.itextpdf.text.Font(bfChinese, 10, Font.NORMAL);//加入document：
            Font tableFont = new com.itextpdf.text.Font(bfChinese, 7, Font.NORMAL);//加入document：
            Font ParagraphFont = new com.itextpdf.text.Font(bfChinese, 16, Font.NORMAL);//加入document：
            Font BigFont = new com.itextpdf.text.Font(bfChinese, 20, Font.NORMAL);//加入document：
            for (int i = 0; i < data.size(); i++) {
                /** 创建章节对象 */
                Map<String, Object> map = data.get(i);
                String deviceName = (String) map.get("deviceName");
                Paragraph title = new Paragraph(deviceName, BigFont);
                title.setAlignment(1);
                title.setSpacingBefore(10);
                title.setSpacingAfter(10);
                Chapter chapter = new Chapter(title, 1);
                chapter.setNumberDepth(0);
                List<String> identifiers = (List<String>) map.get("identifiers");
                List<List<Map<String, String>>> dataList = (List<List<Map<String, String>>>) map.get("data");
                /** 创建章节中的小节 */
                Paragraph titleName = new Paragraph("点位数据", ParagraphFont);
                titleName.setAlignment(1);
                titleName.setSpacingBefore(10);
                titleName.setSpacingAfter(10);
                Section section = chapter.addSection(titleName);
//                if (i != 0) {
//                    section.setTriggerNewPage(true);
//                }
                Paragraph timeTitle = new Paragraph(startTime + " - " + endTime, ParagraphFont);
                timeTitle.setAlignment(1);
                timeTitle.setSpacingAfter(30);
                section.add(timeTitle);
//                Paragraph someSectionText = new Paragraph("点位数据",
//                        font);
//                section.add(someSectionText);
                List<String> active = identifiers.stream().filter(a -> a.contains("__active")).collect(Collectors.toList());
                /** 创建表格对象（包含行列矩阵的表格） */
                PdfPTable t1 = new PdfPTable(identifiers.size() - active.size());// 设置总列宽
                t1.setPaddingTop(5);
                t1.setSpacingBefore(5);
                t1.setSpacingAfter(5);
                t1.setTotalWidth(550);//表格总宽度
                t1.setLockedWidth(true);//锁定宽度
                List<String> activeList = new ArrayList<>();
                activeList.add("日期");
                activeList.add("时间");
                for (String identifier : identifiers) {
                    if (identifier.contains("__active")) {
                        activeList.add(identifier);
                        continue;
                    }
                    PdfPCell c = new PdfPCell(new Paragraph(identifier, font));
                    c.setUseAscender(true);
                    c.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    t1.addCell(c);
                }
                // 第二行开始不需要new Cell()
                for (List<Map<String, String>> dataValue : dataList) {
                    for (Map<String, String> value : dataValue) {
                        if (value.get("name").contains("__active")) {
                            continue;
                        }
                        t1.addCell(new Paragraph(value.get("data"), tableFont));
                    }
                }
                section.add(t1);
                Paragraph titleName2 = new Paragraph("活跃状态", ParagraphFont);
                titleName2.setAlignment(1);
                titleName2.setSpacingBefore(10);
                titleName2.setSpacingAfter(10);
                Section section2 = chapter.addSection(titleName2);
//                if (i != 0) {
//                    section2.setTriggerNewPage(true);
//                }
                section2.add(timeTitle);
                /** 创建表格对象（包含行列矩阵的表格） */
                PdfPTable t2 = new PdfPTable(active.size() + 2);// 设置总列宽
                t2.setPaddingTop(5);
                t2.setSpacingBefore(5);
                t2.setSpacingAfter(5);
                t2.setTotalWidth(550);//表格总宽度
                t2.setLockedWidth(true);//锁定宽度
                for (String identifier : activeList) {
                    PdfPCell c = new PdfPCell(new Paragraph(identifier, font));
                    c.setUseAscender(true);
                    c.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    t2.addCell(c);
                }
                // 第二行开始不需要new Cell()
                for (List<Map<String, String>> dataValue : dataList) {
                    for (Map<String, String> value : dataValue) {
                        if (value.get("name").contains("time")) {
                            t2.addCell(new Paragraph(value.get("data"), tableFont));
                            continue;
                        }
                        if (!value.get("name").contains("__active")) {
                            continue;
                        }
                        String status = null;
                        if (StrUtil.isBlank(Convert.toStr(value.get("data")))) {
                            status = "";
                        }
                        if (StrUtil.equals(Convert.toStr(value.get("data")), "1")) {
                            status = "在线";
                        } else if (StrUtil.equals(Convert.toStr(value.get("data")), "0")) {
                            status = "离线";
                        }
                        t2.addCell(new Paragraph(status, tableFont));
                    }
                }
                section2.add(t2);
                document.add(chapter);
            }
            return true;
        } catch (Exception e2) {
            throw new ClassCastException(e2.getMessage());
        }
    }

}
